using MessagePack;

namespace Crux.Core.Cache.Extensions;
/// <summary>
/// MessageResolver
/// </summary>
public static class MessagePackUtils
{
    static MessagePackUtils()
    {
        MessagePackSerializer.DefaultOptions = MessagePack.Resolvers.ContractlessStandardResolver.Options;
        MessagePackSerializer.DefaultOptions.WithCompression(MessagePackCompression.Lz4BlockArray);
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="valueObject"></param>
    /// <param name="options"></param>
    /// <param name="cancellationToken"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static byte[] Serialize<T>(T valueObject, MessagePackSerializerOptions? options = null, CancellationToken cancellationToken = default)
    {
        using var memoryStream = new MemoryStream();

        MessagePackSerializer.Serialize(memoryStream, valueObject, options, cancellationToken);

        memoryStream.Seek(0, SeekOrigin.Begin);

        return memoryStream.ToArray();
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="valueObject"></param>
    /// <param name="options"></param>
    /// <param name="cancellationToken"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static async Task<byte[]> SerializeAsync<T>(T valueObject, MessagePackSerializerOptions? options = null, CancellationToken cancellationToken = default)
    {
        using var memoryStream = new MemoryStream();

        await MessagePackSerializer.SerializeAsync(memoryStream, valueObject, options, cancellationToken).ConfigureAwait(false);

        memoryStream.Seek(0, SeekOrigin.Begin);

        return memoryStream.ToArray();
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="buffer"></param>
    /// <param name="options"></param>
    /// <param name="cancellationToken"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static T Deserialize<T>(byte[] buffer, MessagePackSerializerOptions? options = null, CancellationToken cancellationToken = default)
    {
        return MessagePackSerializer.Deserialize<T>(buffer, options, cancellationToken);
    }
}